package com.startx.core.system.param;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.startx.core.mvc.define.BodyType;
import com.startx.core.tools.JsonTool;
import com.startx.core.tools.xml.XmlReader;

import io.netty.buffer.ByteBuf;

/**
 * HTTP请求体
 * @author minghu.zhang
 */
public class HttpBody {
	
	/**
	 * 字节缓冲区
	 */
	private ByteBuf buf;
	/**
	 * 请求响应体类型
	 */
	private BodyType type;
	
	public HttpBody(ByteBuf buf,BodyType type) {
		this.buf = buf;
		this.type = type;
	}
	
	/**
	 * 获取字节数组
	 * @return
	 */
	public byte[] bytes() {
		byte[] body = new byte[buf.readableBytes()];

		buf.getBytes(0, body);
		buf.release();
		
		return body;
	}
	
	public Map<String,?> get() {
		return get(type);
	}
	
	/**
	 * 获取map参数
	 * @param type
	 * @return
	 * @throws Exception 
	 */
	public Map<String,?> get(BodyType type) {
		
		try {
			String body = new String(bytes(),"UTF-8");
			
			if(type.equals(BodyType.JSON)) {
				return JsonTool.json2map(body);
			} else if(type.equals(BodyType.XML)) {
				return XmlReader.parseXml(body);
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new HashMap<>();
	}
}
